import {observable, action} from 'mobx';
import {Toast, Tools} from "weaver-mobile";
import {Form,MapPage} from "weaver-mobile-page";
import * as API from '../../api/cptApi';

const getCurrentPosition = MapPage.getCurrentPosition;

const getLabel = Tools.getLabel;
export default class InventoryFormStore {
    @observable isLoading = true;
    @observable inventoryForm = new Form.Store();
    @observable capitalid = '';
    @observable submitID = '';
    @observable viewAttr = '';
    @observable QRCode = '';
    @action
    init = (submitID, cptid, viewAttr) => {
        this.submitID = submitID;
        this.capitalid = cptid;
        this.viewAttr = viewAttr;
        this.getInventoryForm(submitID,cptid, viewAttr);
    };

    @action
    getInventoryForm = (submitID,cptid, viewAttr) => {
        this.isLoading = true;
        let params = {
            cptid: cptid,
            id:submitID
        };
        if (viewAttr) {
            params = {
                ...params,
                viewAttr: viewAttr
            }
        }
        API.getInventoryForm(params).then((res) => {
            this.isLoading = false;
            this.inventoryForm = new Form.Store();
            this.inventoryForm.initForm(res.fieldinfo, '/inventoryForm');
        });
    };
    @action
    getParams = (form) => {
        return form.formParams;
    };

    @action
    updateField = (form, key, value) => {
        form.updateField(key, value);
    };
    @action
    updateFields = (form, fields) => {
        form.updateFields(fields)
    };
    @action
    clearForm = (form) => {
        form.resetFields();
    };
    @action
    cancelSubmit = (history) => {
        history.go(-1);
        this.clearForm(this.inventoryForm);
    };
    @action
    submitInfo = (history) => {
        const paramsAll = this.getParams(this.inventoryForm);
        let re = this.inventoryForm.doValidate();
        if(!re.pass){
            return;
        }
        const params = {
            ...paramsAll
        };
        this.isLoading = true;

        getCurrentPosition().then((result) => {
            if (result.status === 0) { // 定位成功
                    params.address = result.address;
                    params.longitude = result.position[0];
                    params.latitude = result.position[1];
                } else { // 定位失败
                    params.address = "";
                }
            API.doInventory(params).then(res => {
                this.isLoading = false;
                if (res.flag) {
                    Toast.success(getLabel(30700, '操作成功'), 2);
                    history.go(-1);
                } else {
                    Toast.fail(res.msg, 2);
                }
            })
        });

    }
}
